<template>
  <div class="menu-wrapper">
    <office-dialog ref="officeDialog" @confirm="dialogConfirm"/>
    <el-form ref="shopForm" :model="form" :rules="rules" label-width="100px">
      <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">店铺信息</span>
      </div>
      <el-row>
        <el-col :span="6">
          <el-form-item label="门店名称" prop="name">
            <el-input v-model="form.name"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
<!--          <el-form-item label="行业类型" prop="shopCategoryId" :rules="{ required: true, message: '请输入行业分类名', trigger: 'blur' }">-->
<!--            <el-cascader-->
<!--              v-model="form.shopCategoryId"-->
<!--              style="width:100%"-->
<!--              placeholder="行业分类"-->
<!--              :options="productCategoryOptions"-->
<!--              filterable-->
<!--              clearable-->
<!--              :show-all-levels="false"-->
<!--              @change="productCategoryChange"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="行业类型" prop="type">-->
<!--            <el-select style="width: 100%;" v-model="form.storeClassificationId" placeholder="请输入行业分类名">-->
<!--              <el-option v-for="item in storeClassificationOptions" :key="item.label + item.value" :label="item.label"-->
<!--                         :value="item.value" :disabled="typeOneDisabled"/>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="门店类型" prop="type">
            <el-select style="width: 100%;" v-model="form.type" placeholder="请选择类型">
              <el-option v-for="item in typeOptions" :key="item.label + item.value" :label="item.label"
                         :value="item.value" :disabled="typeOneDisabled"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="选择店长" prop="managerId">
            <el-select
              v-model="form.managerId"
              style="width: 100%;"
              placeholder="请选择店长"
              filterable
              :filter-method="queryEmployee"
            >
              <el-option v-for="item in employeeOptions" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联盟店铺" v-if="form.type==4" prop="partnerShopId">
            <el-select v-model="unionName" clearable @clear="clearClick" @change="unionClick" style="width: 100%;" :filter-method="queryUnion"
                       value-key="id" filterable placeholder="请输入联盟店铺手机号">
              <el-option
                v-for="item in unionForm"
                :key="item.id"
                :label="item.name"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="门头照" prop="doorPhoto">
            <single-upload v-model="form.doorPhoto"
                           style="width: 300px;display: inline-block;margin-left: 10px"></single-upload>
          </el-form-item>
        </el-col>
      </el-row>

<!--      <el-row>-->
<!--        <el-col :span="6">-->
<!--          <el-form-item label="结算方式">-->
<!--            <el-select v-model="accountMethodarray" style="width: 100%;" multiple filterable allow-create-->
<!--                       default-first-option placeholder="请选择结算方式" @change="accountMethodchanges">-->
<!--              <el-option label="不结算" value="0"></el-option>-->
<!--              <el-option label="结算货款" value='1'></el-option>-->
<!--              <el-option label="配送费用" value='2'></el-option>-->
<!--              <el-option label="送货员工资" value='3'></el-option>-->
<!--              &lt;!&ndash; <el-option  label="团长佣金" value="4">  </el-option> &ndash;&gt;-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-form-item label="绑定会员"  >-->
<!--            <el-select-->
<!--              v-model="form.memberId"-->
<!--              style="width: 100%;"-->
<!--              placeholder="请选择会员"-->
<!--              filterable-->
<!--              :filter-method="queryMember"-->
<!--            >-->
<!--              <el-option v-for="item in memberOptions" :key="item.id" :label="item.name" :value="item.id" />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--      </el-row>-->


      <el-tabs v-model="activeName">
        <el-tab-pane label="其他信息" name="first">

<!--          <el-row>-->
<!--            <el-col :span="12">-->
<!--              <el-form-item label="门头照" prop="address">-->
<!--                <single-upload v-model="form.doorPhoto"-->
<!--                               style="width: 300px;display: inline-block;margin-left: 10px"></single-upload>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->


          <el-row>
            <el-col :span="12">
              <el-form-item label="所在地" prop="areaName">
                <Distpicker :province="district.province" :city="district.city" :area="district.area"
                            @selected="onSelected"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="详细地址" prop="address">
                <el-input v-model="form.address"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="具体位置" prop="lat">
                <el-button type="primary" round @click="MapShowFn"><i class="el-icon-map-location"/> 定位</el-button>
                <span class="deleted_Row_Headings">({{form.lng}},{{form.lat}})</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="联系人">
                <el-input v-model="form.linkman"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系电话">
                <el-input v-model="form.telephone"/>
              </el-form-item>
            </el-col>
          </el-row>

<!--          <el-row>-->
<!--            <el-col :span="24">-->
<!--              <el-form-item label="店铺详情" prop="address">-->
<!--                &lt;!&ndash;            <el-input type="textarea" v-model="form.content" />&ndash;&gt;-->
<!--                <tinymce v-model="form.content" :height="400"/>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->


        </el-tab-pane>
<!--        <el-tab-pane label="打印管理" name="second">-->
<!--          <el-row>-->
<!--            <el-col :span="6">-->
<!--              <el-form-item label="打印机用户">-->
<!--                <el-input v-model="form.printeru"/>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->
<!--          <el-row>-->
<!--            <el-col :span="6">-->
<!--              <el-form-item label="打印机密钥">-->
<!--                <el-input v-model="form.printerp"/>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->
<!--          <el-row>-->
<!--            <el-col :span='6'>-->
<!--              <el-form-item label="自动打印">-->
<!--                <el-switch-->
<!--                  @change="elswitch"-->
<!--                  v-model="form.autoPrint"-->
<!--                  active-color="#13ce66"-->
<!--                  inactive-color="#ff4949"/>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->

<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="饿了么" name="third">-->

<!--          <div style="color:red;margin-bottom:20px">*请确保饿了么店铺ID输入正确，以免接收不到订单！</div>-->
<!--          <div style="display:flex;align-items: center;">-->
<!--            <el-form-item label="饿了么店铺Id">-->
<!--              <el-input v-model="form.elemeShopId" style="width:300px"/>-->
<!--            </el-form-item>-->
<!--            <div style="margin-left: 10px; font-size: 15px;color:rgb(70,166,255)" @click="imgfunctiom">(点击查看如果获取店铺Id)-->
<!--            </div>-->
<!--          </div>-->
<!--          <el-form-item label="点击前往授权" style="margin-bottom:80px">-->
<!--            <el-button type="primary" @click="element">&nbsp&nbsp前往授权&nbsp&nbsp</el-button>-->
<!--            <el-button type="primary" @click="findelement">&nbsp&nbsp查看授权&nbsp&nbsp</el-button>-->
<!--          </el-form-item>-->

<!--        </el-tab-pane>-->
      </el-tabs>
      <el-form-item>
        <el-button v-permission="['shop.edit']" type="primary" :loading="clicked" @click="updateshop('shopForm')">
          &nbsp&nbsp完 成&nbsp&nbsp
        </el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      title="请选择具体位置"
      :visible.sync="MapShow"
      top="5vh"
      width="800px"
      :before-close="handleClose"
    >
      <Map :initcenter="[form.lng, form.lat]" @getMap="getMap"/>
      <span slot="footer" class="dialog-footer">
        <el-button @click="MapShow = false">取 消</el-button>
        <el-button type="primary" @click="savelngLat">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="请按照如图所示查看Id"
      :visible.sync="imgshow"
      top="5vh"
      width="800px"
    >
      <el-tabs v-model="imgactiveName">
        <el-tab-pane label="PC版" name="first">
          <el-image
            style="width: 400px; height: 400px"
            src="http://rzico.oss-cn-shenzhen.aliyuncs.com/elememt.png"
            :preview-src-list="srcList"></el-image>
          <!-- <img style="width:90%" src="http://rzico.oss-cn-shenzhen.aliyuncs.com/elememt.png" alt=""> -->
        </el-tab-pane>
        <el-tab-pane label="APP版" name="second">
          <!-- <div style="display: flex; justify-content: center; align-items: center;">
          <div style="height:800px;overflow: auto;">
          <img style="width:50%" src="http://rzico.oss-cn-shenzhen.aliyuncs.com/ca0b86f6c332b9581ef930545dd89a8.png" alt="">
          <img style="width:50%" src="http://rzico.oss-cn-shenzhen.aliyuncs.com/ac5f9e939d51761a80c7ce6a65b2bac.png" alt="">
          <img style="width:50%" src="http://rzico.oss-cn-shenzhen.aliyuncs.com/b756c14ea7c7c706df72f04a79ca627.png" alt="">
          </div>
          </div> -->
          <el-image
            style="width: 400px; height: 400px"
            src="http://rzico.oss-cn-shenzhen.aliyuncs.com/ca0b86f6c332b9581ef930545dd89a8.png"
            :preview-src-list="srcListagein"></el-image>
        </el-tab-pane>
      </el-tabs>

    </el-dialog>
    <el-dialog
      :visible.sync="creadImageShow"
      top="5vh"
      width="500px"
      :before-close="handleClose"
    >
      <div>
        <a :href="code" target="_blank" style="color:rgb(70,166,255)">点击前往授权或扫描二维码</a>
      </div>
      <div style="width:100%;display: flex; justify-content: center;margin-top:30px">
        <img :src="creadImage" alt="">
      </div>


    </el-dialog>
  </div>
</template>
<style scoped>
.menu-wrapper {
  margin: 15px;
}
</style>
<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import {EventBus} from '@/api/eventBus'
import utils from '../../utils/utils.js'
import OfficeDialog from '@/components/OfficeDialog'
import {find, update, getAuthUrl, selectToken, listByOwnerPhone} from '@/api/shop'
import Distpicker from '@/components/Distpicker/Distpicker'
import Map from '@/components/GaodeMap/index'
import {list as sysEmployeeList} from '@/api/sysEmployee'
import Tinymce from '@/components/Tinymce'
import singleUpload from '@/components/Upload/singleUpload'
import {list as productCategoryList} from "@/api/productCategory";
import {list as shopCategoryList} from "@/api/shopCategory";




export default {
  name: 'shop-edit',
  directives: {permission},
  filters: {},
  components: {
    OfficeDialog,
    Distpicker,
    Map,
    Tinymce,
    singleUpload
  },
  data() {
    return {
      productCategoryOptions:[],
      code: "",
      creadImageShow: false,
      creadImage: "",
      tabsHeight: "",
      srcListagein: [
        "http://rzico.oss-cn-shenzhen.aliyuncs.com/ca0b86f6c332b9581ef930545dd89a8.png",
        "http://rzico.oss-cn-shenzhen.aliyuncs.com/ac5f9e939d51761a80c7ce6a65b2bac.png",
        "http://rzico.oss-cn-shenzhen.aliyuncs.com/b756c14ea7c7c706df72f04a79ca627.png"
      ],
      srcList: ["http://rzico.oss-cn-shenzhen.aliyuncs.com/elememt.png"],
      imgactiveName: "first",
      imgshow: false,
      activeName: "first",
      id: '',
      tempLng: '',
      tempLat: '',
      MapShow: false,
      district: {},
      clicked: false, // 按钮防双击
      topName: '',
      typeOneDisabled: false, // 公司类型是否禁用
      typeTwoDisabled: false, // 部门类型是否禁用
      typeOptions: [
        {value: 0, label: '直营店'},
        {value: 3, label: '加盟店'},
        {value: 4, label: '联盟店'},
      ],
      storeClassificationOptions:[],
      employeeOptions: [],
      form: {
        autoPrint: false,
        id: '',
        name: '',
        officeId: '',
        linkman: '',
        telephone: '',
        status: 0,
        type: 0,
        modifyDate: '',
        address: '', // 地址
        lng: '', // 经度
        lat: '', // 纬度
        printeru: '',
        printerp: '',
        elemeShopId: "",
        partnerShopId: '',
        partnerEnterpriseId: '',
        doorPhoto:''
      },
      unionForm: [],
      unionName: '',
      rules: {
        name: [
          {required: true, message: '请输入组织名称', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        officeId: [
          {required: true, message: '请选择所属部门'}
        ],
        linkman: [
          {required: true, message: '请输入联系人', trigger: 'blur'}
        ],
        telephone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'}
        ],
        areaName: [
          {required: true, message: '请选择仓库所在地址'}
        ],
        address: [
          {required: true, message: '请选择仓库详细地址'}
        ],
        lat: [
          {required: true, message: '请选择仓库具体坐标'}
        ],
        type: [
          {required: true, message: '请选择类型', trigger: 'blur'}
        ],
        managerId: [
          {required: true, message: '请选择店长', trigger: 'blur'}
        ],
        accountMethod: [
          {required: true, message: '请选择结算方式', trigger: 'blur'}
        ],
        partnerShopId: [
          {required: true, message: '请选择联盟店', trigger: 'blur'}
        ],
      }
    }
  },
  watch: { // 路由地址不变的情况下,如果id变化则重新获取数据
    $route(newVal, oldVal) {
      console.log(newVal)
      if (newVal.name == 'shop-edit' && newVal.query.id != this.id) {
        this.getData()
      }
    }
  },
  created() {
    this.getData()
    this.queryMember('')
    this.queryEmployee('')
    this.loadShopCategory()

  },
  methods: {
    loadShopCategory() {
      shopCategoryList().then(response => {
        this.productCategoryOptions = this.formatProductCategoryData(response.data)
      }).catch(error => {
      })
    },
    formatProductCategoryData(data) {
      const _this = this
      const productCategoryOptions = []
      if (data.length > 0) {
        data.map(item => {
          const productCategoryOptionsItem = {}
          productCategoryOptionsItem.value = item.id
          productCategoryOptionsItem.label = item.name
          if (item.childrens.length > 0) {
            productCategoryOptionsItem.children = _this.formatProductCategoryData(item.childrens)
          }
          productCategoryOptions.push(productCategoryOptionsItem)
        })
      }
      return productCategoryOptions
    },
    // 商品分类选择事件
    productCategoryChange(val) {
      this.form.shopCategoryId = val[val.length - 1]
    },
    elswitch(data) {
      console.log(data)
      this.form.autoPrint = data
    },

    findelement() {
      const params = new URLSearchParams();
      params.append('shopId', this.id)
      selectToken(params).then(res => {
        this.$message({
          showClose: true,
          message: res.content,
          type: 'success'
        });

      })

    },
    element() {
      const params = new URLSearchParams();
      params.append('elemeShopId', this.form.elemeShopId)
      getAuthUrl(params).then(res => {
        this.creadImageShow = true
        this.code = res.content
        this.creadImage = process.env.VUE_APP_BASE_API + '/zxing/createImage?data=' + encodeURIComponent(this.code)

      })
    },
    imgfunctiom() {
      this.imgshow = true
    },
    accountMethodchanges(val) {
      this.form.accountMethod = ''
      val.forEach(item => {
        this.form.accountMethod += item
      })

    },
    queryMember(query) {
      clearTimeout(this.memberMark)
      this.memberMark = setTimeout(() => {
        this.memberOptions = []
        // sysEmployeeList({ employeeType:2,name: query }).then(res => {
        //   this.memberOptions = res.data.data
        // }).catch(err => { console.log(err) })
        memberlist().then(res => {
          this.memberOptions = res.data.data
        }).catch(err => { console.log(err) })
      }, 300)
    },
    queryEmployee(query) {
      clearTimeout(this.employeeMark)
      this.employeeMark = setTimeout(() => {
        this.employeeOptions = []
        sysEmployeeList({ employeeType:0,name: query }).then(res => {
          this.employeeOptions = res.data.data
        }).catch(err => { console.log(err) })
      }, 300)
    },
    getData() {
      console.log(this.$route.query.id)
      this.id = this.$route.query.id
      find(this.id).then(response => {
        console.log('成功', response)
        this.form = response.data.shop
        //处理结算方式
        this.accountMethodarray = this.form.accountMethod.split('')
        let array = []
        this.accountMethodarray.forEach(item => {
          array.push(item)
        })
        this.accountMethodarray = array
        console.log('86768786787878678678787867687');
        console.log(this.accountMethodarray);
        const obj = {
          name: response.data.managerName,
          id: this.form.managerId
        }
        this.sysEmployeeOptions.unshift(obj)
        this.topName = response.data.officeName
        console.log(this.form)
        const reg = /.+?(省|市|自治区|自治州|县|区)/g
        // console.log(this.form.address.match(reg)[0])
        this.district.province = this.form.areaName.match(reg)[0]
        this.district.city = this.form.areaName.match(reg)[1]
        this.district.area = this.form.areaName.match(reg)[2]
        this.unionName = response.data.parnterShopName
      }).catch(error => {
        console.log('失败', error)
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {
        })
    },
    MapShowFn() {
      this.MapShow = !this.MapShow
    },
    getMap(lng, lat) {
      console.log(lng, lat)
      // 定义变量保存经纬度
      this.tempLng = lng
      this.tempLat = lat
    },
    savelngLat() {
      this.form.lng = this.tempLng
      this.form.lat = this.tempLat
      this.MapShow = false
    },
    onSelected(val) {
      if (!utils.isNull(val.city) && !utils.isNull(val.area) && !utils.isNull(val.area.code)) {
        this.form.areaId = val.area.code
        this.form.areaName = val.province.value + val.city.value + val.area.value
        // this.form.areaName = val.area.value
      }
    },
    dialogShow() {
      console.log('点击了')
      this.$refs.officeDialog.show()
    },
    /* dialogConfirm(val) {
      this.form.officeId = val.id
      this.topName = val.name
      if (val.type == 0) {
        this.form.type = 1
        this.typeOneDisabled = false
        this.typeTwoDisabled = false
      } else {
        this.form.type = 1
        this.typeOneDisabled = true
      }
    }, */
    dialogConfirm(val) {
      this.form.officeId = val.id
      this.topName = val.name
    },
    updateshop(form) {
      const _this = this
      console.log(this.$refs[form])
      console.log(this.form)
      this.$refs[form].validate((valid) => {
        if (valid) { // 校验表单
          _this.clicked = true
          const date = new Date()
          this.form.modifyDate = date
          console.log(_this.form);
          update(_this.form).then(response => {
            console.log(response)
            _this.clicked = false
            EventBus.$emit('shop-edit', response.data)
            _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
              _this.$router.push({
                path: '/shop/list'
              })
            })// 关闭当前tab回到列表
          }).catch(error => {
            _this.clicked = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    queryUnion(data) {
      console.log(data)
      var _this = this
      listByOwnerPhone({ownerPhone: data}).then(res => {
        console.log(res)
        _this.unionForm = res.data.data
      })
    },
    unionClick(data) {
      console.log(data)
      this.unionName = data.name
      this.form.partnerShopId = data.id
      this.form.partnerEnterpriseId = data.enterpriseId
    },
    clearClick(){
      this.unionName = ''
      this.form.partnerShopId = ''
      this.form.partnerEnterpriseId = ''
    }
  }
}
</script>
